import Vue from 'vue'
import VueRouter from 'vue-router'
import config from './config'
import store from '../store'

// 1. 安装
Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

// 2. 创建路由对象
const router = new VueRouter(config)

// 3. 导航守卫
router.beforeEach(function (to, from, next) {
  if (to.meta.auth) {
    // 需要登录才能访问
    if (store.state.loginUser.isLoading) {
      next({ name: 'Auth', query: { returnurl: to.fullPath } })
    } else if (store.state.loginUser.data) {
      next() // 允许访问
    } else {
      next({ name: 'Login' })
    }
  }
  // next 是一个函数,可以通过该函数跳转到指定的路由
  next()
})

export default router
